package com.ljc.cjgl.service;

import java.util.HashSet;
import java.util.List;
import java.util.Optional;

import org.abyss.data.specifications.Rule;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import org.springframework.ui.ModelMap;

import com.ljc.cjgl.entitiy.Student;
import com.ljc.cjgl.entitiy.Teacher;
import com.ljc.cjgl.form.TeacherForm;
import com.ljc.cjgl.repository.TeacherRepository;

@Service
public class TeacherService {
	@Autowired
	private TeacherRepository teacherDAO;

	
	public List<Teacher> findAll(){
		return teacherDAO.findAll();
	}
	
	public Teacher findById(Integer id) {
		Optional<Teacher> optional = teacherDAO.findById(id);
		if(optional.isPresent()) {
			return optional.get();
		}
		return null;
	}
	
	public Page<Teacher> findAll(Specification<Teacher> specification,Pageable pageable){
		return teacherDAO.findAll(specification, pageable);
	}

	public void save(TeacherForm form) {
		Teacher model=new Teacher();
		if(form.getId()!=null) {
			model=findById(form.getId());
		}
		BeanUtils.copyProperties(form, model,"id");
		teacherDAO.save(model);
	}

	public synchronized boolean delete(List<Teacher> teachers) {
		try {
			for (Teacher teacher : teachers) {
				teacherDAO.deleteById(teacher.getId());
			}
			return true;
		} catch (Exception e) {
			return false;
		}
	}

	public Teacher findByNameAndPwd(String userName, String pwd) {
		HashSet<Rule> rules=new HashSet<>();
		rules.add(Rule.property("name").equal(userName));
		rules.add(Rule.property("pwd").equal(pwd));
		Specification<Teacher> specification = Rule.and(rules).toSpecification();
		List<Teacher> list=teacherDAO.findAll(specification);
		if(!list.isEmpty()) {
			Teacher teacher = list.get(0);
			return teacher;
		}
		return null;
	}

	public void save(Teacher teacher) {
		teacherDAO.save(teacher);
	}
}
